import 'package:meta/meta.dart';
import 'package:baby/UI/Widgets/HtmlContent/TransformUnit.dart';


class TransformPipeLine<FEATURE_CONTEXT, DATA> {
	List<TransformUnit<FEATURE_CONTEXT, DATA>> _pipes = [];
	List<TransformUnit<FEATURE_CONTEXT, DATA>> get pipes => _pipes;

	final FEATURE_CONTEXT featureContext;
	DATA data;
	var _executionIndex = 0;


  TransformPipeLine({@required this.featureContext});

	DATA start(DATA data){
		_executionIndex = 0;
		processWith(data);
		return this.data;
	}

	DATA process(DATA data){
		var innerPipeLines = TransformPipeLine<FEATURE_CONTEXT, DATA>(featureContext: featureContext);
		_pipes.forEach((pipe) => innerPipeLines.installPipe(pipe));
		data = innerPipeLines.start(data);
		innerPipeLines._pipes.forEach((pipe) => pipe.pipeLineContext = this);
		return data;
	}

	void endWith(DATA data) {
		_executionIndex = _pipes.length;
		processWith(data);
	}

	void installPipe(TransformUnit<FEATURE_CONTEXT, DATA> unit){
		unit.pipeLineContext = this;
		this._pipes.add(unit);
	}

	void uninstallPhase(TransformUnit<FEATURE_CONTEXT, DATA> unit){
		_pipes.remove(unit);
	}

	void processWith(DATA data) {
		this.data = data;
		for (; _executionIndex < _pipes.length; _executionIndex++){
			_pipes[_executionIndex].execution(featureContext, data);
		}
	}
}

